<template>
  <div>
    <!-- 查询表单 -->
    <el-form :model="queryObj">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="合同编号">
            <el-input v-model="queryObj.contractNo" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="客户姓名">
            <el-input v-model="queryObj.name" placeholder="请输入客户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号">
            <el-input v-model="queryObj.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买学科">
            <el-select v-model="queryObj.subject" placeholder="请选择购买学科">
              <el-option
                v-for="item in optionsSubject"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="购买课程">
            <el-select v-model="queryObj.courseName" placeholder="请选择购买课程">
              <el-option
                v-for="item in optionsCourseName"
                :key="item.label"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="日期选择">
            <el-date-picker
              v-model="queryObj.createTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="text-right">
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" @click="addClick">+添加合同</el-button>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane :status="0" :label="c0" name="first" />
      <el-tab-pane :status="1" :label="c1" name="second" />
      <el-tab-pane :status="2" :label="c2" name="third" />
      <el-tab-pane :status="3" :label="c3" name="fourth" />
      <el-tab-pane :status="4" :label="c4" name="five" />
    </el-tabs>
    <!-- 展示表格 -->
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column label="序号" width="180" type="index" :index="Nindex" />
      <el-table-column prop="contractNo" label="合同编号" width="180" />
      <el-table-column prop="name" label="客户姓名" width="180" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="subject" label="购买学科" />
      <el-table-column prop="courseName" label="购买课程" />
      <el-table-column prop="status" :formatter="formatStatus" label="合同状态" />
      <el-table-column prop="createTime" sortable label="创建时间" />
      <el-table-column sortable label="操作" width="180">
        <template #default="{row}">
          <el-button @click="preview(row)">修改</el-button>
          <el-button @click="check(row)">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      hide-on-single-page
      :current-page="queryObj.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="queryObj.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 添加弹出层 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="addForm" :rules="rules" :model="addForm" label-width="80px">
        <el-form-item prop="contractNo" label="合同编号">
          <el-input v-model="addForm.contractNo" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item prop="name" label="客户姓名">
          <el-input v-model="addForm.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop="subject" label="购买学科">
          <el-select v-model="addForm.subject" placeholder="请选择">
            <el-option
              v-for="item in optionsSubject"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="courseName" label="购买课程">
          <el-select v-model="addForm.courseName" placeholder="请选择">
            <el-option
              v-for="item in optionsCourseName"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="合同状态">
          <el-select v-model="addForm.status" placeholder="请选择">
            <el-option
              v-for="item in optionsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间">
          <el-date-picker
            v-model="addForm.createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-form-item prop="fileName" label="选择合同">
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            :http-request="httpRequest"
            :file-list="fileList"
            :limit="3"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">仅支持1M以内且jpeg，jpg，png，gif,pdf格式的文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="enterClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片弹出层 -->
    <el-dialog
      title="文件预览"
      :close-on-click-modal="false"
      :visible.sync="dialogImg"
      width="80%"
      :before-close="closeImg"
    >
      <img style="max-width: 100%;" :src="diaImgSrc" alt="">
      <span slot="footer" class="dialog-footer">
        <el-button @click="change(3)">驳回</el-button>
        <el-button type="primary" @click="change(2)">通过</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getListApi, addContractApi, getOneDetailApi, getTypeCountApi, changeContractApi, ContractApi } from '@/api/contract'
import cos from '@/utils/cos'
import { Message } from 'element-ui'
export default {

  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      activeName: 'first',
      // 全部数据
      tableData: [],
      dialogVisible: false,
      dialogImg: false,
      queryObj: {
        page: 1,
        pageSize: 10,
        contractNo: '',
        id: ''
      },
      // 添加合同表单
      addForm: {
        contractNo: '',
        name: '',
        phone: '',
        subject: '',
        courseName: '',
        status: '',
        createTime: '',
        fileName: ''
      },
      rules: {
        contractNo: [
          { required: true, message: '请输入合同编号', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '请输入科目', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请输入状态', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        // createTime: [
        //   { required: true, message: '请输入创建时间', trigger: 'blur' },
        //   { type: 'string', message: '请输入有效的日期', trigger: 'blur' }
        // ],
        fileName: [
          { required: true, message: '请上传文件', trigger: 'change' }
        ]
      },
      optionsStatus: [{
        value: '1',
        label: '待审核'
      }, {
        value: '2',
        label: '已通过'
      }, {
        value: '3',
        label: '已驳回'
      }],
      optionsCourseName: [{
        label: 'Python'
      }, {
        label: 'C++'
      }, {
        label: 'JavaScript'
      }, {
        label: 'Artificial Intelligence'
      }, {
        label: 'Cybersecurity'
      }, {
        label: 'Web Development'
      }, {
        label: 'Cloud Computing'
      }, {
        label: 'Database Management'
      }, {
        label: 'Network Administration'
      }, {
        label: 'Mobile App Development'
      }
      ],
      optionsSubject: [
        { label: 'JavaScript基础' },
        { label: 'JavaScript进阶' },
        { label: 'JavaScript原理' },
        { label: 'Vue.js基础' },
        { label: 'Vue.js进阶' },
        { label: 'Vue.js原理' },
        { label: 'React.js基础' },
        { label: 'React.js进阶' },
        { label: 'React.js原理' }
      ],
      total: 0,
      // 文件列表
      fileList: [],
      title: '',
      c0: '',
      c1: '',
      c2: '',
      c3: '',
      c4: '',
      diaImgSrc: '',
      id: ''
    }
  },
  created() {
    this.getList()
    this.getTypeCount()
  },
  methods: {
    formatStatus(a = undefined, b = undefined, c) {
      const mapType = {
        1: '待审核',
        2: '已通过',
        3: '已驳回',
        4: '全部完成'
      }
      return mapType[c]
    },
    // 合同修改
    async change(status) {
      // this.addForm.contractNo = +this.addForm.contractNo
      // this.addForm.id = String(this.addForm.id)
      const res = await ContractApi(this.id, status)
      if (res.code === 500) {
        this.$message.error('修改失败!')
        this.dialogImg = false
        return
      }
      this.$message.success('修改成功!')
      this.dialogImg = false
      this.getList()
    },
    // 点击预览
    async preview(a) {
      this.dialogVisible = true
      this.title = '修改'
      this.id = a.id
      const res = await getOneDetailApi(a.id)
      const { id, contractNo, name, phone, subject, courseName, status, createTime, fileName } = res.data
      this.addForm = { id, contractNo, name, phone, subject, courseName, status, createTime, fileName }
    },
    // 点击审核
    check(a) {
      this.id = a.id
      this.dialogImg = true
      this.diaImgSrc = a.fileName
    },
    // 添加合同
    async addContract() {
      const res = await addContractApi(this.addForm)
      if (res.code === 1) {
        Message.success('添加成功！')
        this.getList()
      } else {
        Message.error('添加失败！')
      }
      this.dialogVisible = false
    },
    // 检验类型和大小
    beforeUpload(file) {
      const type = ['image/jpeg', 'application/pdf', 'image/jpg', 'image/png', 'image/gif']
      if (!type.includes(file.type)) {
        this.$message.error('仅支持jpeg，jpg，png，gif,pdf格式的文件')
        return false
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('仅支持1M以内的图片')
        return false
      }
    },
    onExceed() {
      this.$message.info('数量超出限制')
    },
    // 覆盖默认上传
    httpRequest({ file }) {
      // const curFile = this.fileList.find(el => el.uid === file.uid)
      // curFile.status = 'uploading'
      cos.uploadFile({
        Bucket: 'wym-1315554314', /* 填写自己的 bucket，必须字段 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: +new Date() + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */

      }, (err, data) => {
        if (err) {
          this.$message.error('上传失败')
        }
        console.log(data)
        this.addForm.fileName = '//' + data.Location
      })
    },
    // 点击表单确定按钮
    async enterClick() {
      // 兜底校验
      this.$refs.addForm.validate(async f => {
        if (!f) return
        // 修改还是添加?
        if (this.title === '修改') {
          const res = await changeContractApi(this.addForm)
          if (res.code === 500) {
            Message.error('修改失败！')
            return
          }
          Message.success('修改成功！')
        } else {
          // 调用添加接口
          await this.addContract()
        }
        this.dialogVisible = false
        this.getList()
      })
    },
    // 点击重置
    reset() {
      this.queryObj = {
        page: 1,
        pageSize: 10
      }
      this.getList()
    },
    search() {
      this.getList()
    },
    // 页容量切换
    handleSizeChange(val) {
      this.queryObj.pageSize = val
      this.getList()
    },
    // 第几页切换
    handleCurrentChange(val) {
      this.queryObj.page = val
      this.getList()
    },
    // 处理分页序号
    Nindex(index) {
      // 当前页数 - 1 * 每页数据条数 + 1
      return index + 1 + (this.queryObj.page - 1) * this.queryObj.pageSize
    },
    // 切换合同状态触发
    handleClick(val) {
      this.queryObj.status = val.$attrs.status
      this.getList()
    },
    closeImg() {
      this.dialogImg = false
    },
    // 弹出层关闭前
    handleClose() {
      this.dialogVisible = false
      // 重置校验
      this.$refs.addForm.resetFields()
    },
    // 点击添加合同按钮
    addClick() {
      this.dialogVisible = true
      this.title = '添加合同'
    },
    // 请求合同列表
    async getList() {
      const res = await getListApi(this.queryObj)
      this.tableData = res.data.records
      this.total = res.data.total
    },
    // 请求分类数量
    async getTypeCount() {
      const res = await getTypeCountApi()
      console.log(res.data)
      if (res.code === 1) {
        this.c0 = `全部（${res.data[0]}）`
        this.c1 = `待审核（${res.data[1]}）`
        this.c2 = `已通过（${res.data[2]}）`
        this.c3 = `已驳回（${res.data[3]}）`
        this.c4 = `全部完成（${res.data[4]}）`
      }
    }

  }
}
</script>
<style lang="scss" >
.el-select,.el-date-editor.el-input{
  width: 100%;
}
.text-right {
  text-align: right;
}

.el-pagination {
  float: right;
  margin-top: 40px;

  button {
    height: 30px;
    width: 30px;
    border: 2px solid #090B14;
    border-radius: 4px;

    .el-icon {
      font-size: 15px !important;
      font-weight: 100;
      color: #090B14;
    }
  }

  .el-pagination__jump {
    font-size: 15px !important;
    font-weight: 100;
    color: #090B14;
    line-height: 45px;

    .el-input.el-pagination__editor {
      width: 140px;
    }

    input {
      overflow: hidden;
      width: 96px;
      overflow: auto;
      height: 30px !important;
      color: #090B14;
      font-size: 20px;
      border: 2px solid #090B14;
      border-radius: 4px;
    }
  }

  ul {
    li {
      margin-left: 30px !important;
      height: 30px;
      width: 30px;
      font-size: 20px;
      color: #090B14 !important;
      font-weight: 100;
      line-height: 30px;
      border: 2px solid #090B14;
      border-radius: 4px;
    }

    li.el-icon {
      margin-right: 30px;
      line-height: 30px;
    }

    li:last-child {
      margin-right: 30px;
      display: none;
    }

    li.active {
      color: #ffffff !important;
      background: #6B8CFF;
    }

    li.active+li {
      border-left: 2px solid #090B14;
    }
  }

}
</style>
